# THANKS TO:
# https://github.com/yaronzz/Tidal-Media-Downloader
# https://github.com/lucaslg26/TidalAPI
# https://pypi.org/project/tidalapi

from urllib.request import urlopen
import requests
import uuid
import pyaes

import tidal.tidal_api
import tidal.track_stream
import tidal.track
import tidal.album
import tidal.artist

from cache.cache import cache
from cache.constants import TIDAL_TRACK

PRIVATE_API_URL = "https://api.tidalhifi.com/v1/%s"

class Tidal:
  def __init__(self):
    self.api = tidal.tidal_api.TidalAPI()
    self.user_id = None
    self.username = None

  def login(self, username, password):
    data = self.api.login(username, password)
    self.user_id = data["userId"]

    profile_data = self.get_profile_data()
    data = {
      "user_id": data["userId"],
      "username": profile_data["username"]
    }
    self.username = data["username"]

    return data

  def get_profile_data(self):
    if self.user_id == None:
      raise 'not logged in'
    return self.api.get_user_data(self.user_id)

  def get_stream(self, track_id, quality):
    return tidal.track_stream.TidalTrackStream.grab_or_create(
      track_id,
      raw_data = self.api.get_stream_info(track_id, quality).json()
    )

  def get_track(self, track_id):
    cache_key = TIDAL_TRACK % track_id
    track_data = self.api.get_track_data(track_id).json()
    print(track_data)
    if cache.has(cache_key):
      track = cache.get(cache_key)
    else:
      track = tidal.track.TidalTrack(track_data["id"], track_data["title"])
      cache.set(cache_key, track)
    track.set_raw_data(track_data)
    return track

  def get_album_full_data(self, album_id):
    return {**self.api.get_album_data(album_id).json(),
            "songs": self.api.get_album_tracks_data(album_id).json()}
  def get_album(self, album_id):
    return tidal.album.TidalAlbum.grab_or_create(
      album_id,
      raw_data = self.get_album_full_data(album_id),
    )

  def get_artist(self, artist_id):
    return tidal.artist.TidalArtist.grab_or_create(
      artist_id, raw_data = self.api.get_artist_data(artist_id)
    )

